package com.chif.demo.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

/**
 * 分区顺序
 * 通过实现MessageQueueSelector选择算法将不同类型的消息分别发到queue中
 */
public class OrderedProducer {

    public static void main(String[] args) throws Exception {
        //创建一个producer，参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("pg");
        producer.setNamesrvAddr("192.168.10.100:9876");

        //设置发送超时时限为5s，默认3s
        producer.setSendMsgTimeout(5000);
        //开启生产者
        producer.start();

        for (int i = 0; i < 100; i++) {
            Integer orderId=i;
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("TopicA", "TagA", body);
            //将orderId作为消息key
            msg.setKeys(orderId.toString());
            //同步发送
            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                //具体的选择算法
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    //以下是用消息key作为选择key
                    String keys = msg.getKeys();
                    Integer id = Integer.valueOf(keys);

                    //以下是用消息arg作为选择key
                    //Integer id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }
                //orderId参数和arg参数是同一个
            }, orderId);
            System.out.println(sendResult);
        }

        //关闭producer
        producer.shutdown();

    }
}
